<template>
  <TopHeader :local-city-data="localCityData" />
  <div class="container">
    <input
      type="text"
      class="form-control"
      @focus="isFocused = true"
      @blur="isFocused = false"
      :class="{ focused: isFocused }"
      placeholder="请输入城市名称"
      v-model="newCityName"
      @input="fetchCities"
    />

    <div v-if="filteredCities.length > 0">
      <ul>
        <li v-for="city in filteredCities" :key="city" class="city-item">
          <div @click="navigateToSearchView(city)" style="cursor: pointer">
            {{ city }}
          </div>
        </li>
      </ul>
    </div>

    <!-- 仅在没有匹配结果时显示本地存储城市 -->
    <div v-if="filteredCities.length === 0 && cities.length > 0">
      <ul>
        <li v-for="city in cities" :key="city" class="city-item">
          <div @click="navigateToCity(city)" style="cursor: pointer">
            {{ city }}
          </div>
          <div class="buttons-container">
            <button @click="viewCity(city)">查看</button>
            <!-- 查看城市 -->
            <button @click="deleteCity(city)">删除</button>
            <!-- 删除城市 -->
          </div>
        </li>
      </ul>
    </div>

    <div v-else class="no-cities">
      暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
    </div>

    <div class="weather-title">近期天气</div>
    <EchartsModel :local-city-data="localCityData" />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { getIpData, getAdCodeData, getWeatherData } from "@/api/index";
import EchartsModel from "@/components/EchartsModel.vue";
import TopHeader from "../components/TopHeader.vue";

const router = useRouter();
const isFocused = ref(false);
const newCityName = ref("");
const cities = ref([]);
const filteredCities = ref([]); // 用于存储匹配的城市
const localCityData = ref({});

onMounted(async () => {
  try {
    const storedCities = JSON.parse(localStorage.getItem("cities")) || [];
    cities.value = storedCities;

    const res = await getIpData();
    const adcode = await getAdCodeData(res.city);
    const weatherData = await getWeatherData(adcode.geocodes[0].adcode);
    localCityData.value = weatherData;
  } catch (error) {
    console.error("获取IP数据时发生错误:", error);
  }
});

// 获取城市建议
const fetchCities = async () => {
  if (newCityName.value) {
    try {
      const adcodeData = await getAdCodeData(newCityName.value);
      filteredCities.value = adcodeData.geocodes.map(
        (code) => code.formatted_address
      ); // 更新匹配的城市列表
    } catch (error) {
      console.error("获取城市建议时发生错误:", error);
    }
  } else {
    filteredCities.value = [];
  }
};

// 点击城市名称时跳转到 SearchView 页面
const navigateToSearchView = (city) => {
  router.push({ name: "search", params: { cityName: city } });
};

// 跳转到search页面（查看已保存的城市）
const navigateToCity = (city) => {
  router.push({ name: "search", params: { cityName: city } });
};

// 查看城市
const viewCity = (city) => {
  router.push({ name: "search", params: { cityName: city } });
};

// 删除城市
const deleteCity = (city) => {
  cities.value = cities.value.filter((c) => c !== city);
  localStorage.setItem("cities", JSON.stringify(cities.value)); // 更新本地存储
};
</script>

<style lang="scss" scoped>
.container {
  height: calc(100vh - 80px);
  padding: 0 10%;
  background-color: #00668a;

  .form-control {
    border: none;
    width: 100%;
    padding: 10px;
    margin-top: 15px;
    background-color: #00668a;
    border-bottom: 1px solid white;
    transition: box-shadow 0.25s ease;
    box-shadow: none;
    outline: none;
    font-size: 16px;
  }

  .form-control.focused {
    box-shadow: 0 4px 5px rgba(0, 0, 0, 0.2);
    border-bottom: none;
  }

  .city-item {
    padding: 20px; /* Increase padding for more space */
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center; /* Vertically center the city name */
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    color: white;
    position: relative;
    overflow: hidden;
    background-color: #004e71;
    transition: background-color 0.3s ease;
    margin-bottom: 10px; /* Add space between items */
  }

  .city-item:hover {
    background-color: #00668a;
  }

  .buttons-container {
    display: flex;
    justify-content: flex-end;
    align-items: center; /* Vertically center the buttons */
    position: absolute;
    right: 0;
    top: 50%; /* Center the container vertically */
    transform: translateY(-50%); /* Adjust the position */
    opacity: 0;
    transition: opacity 0.3s ease, transform 0.3s ease;
  }

  .city-item:hover .buttons-container {
    opacity: 1;
    transform: translateY(-50%); /* Maintain vertical centering when hovering */
  }

  .city-item button {
    margin-left: 10px;
    padding: 10px 20px;
    background-color: #fac31c;
    color: white;
    cursor: pointer;
    box-shadow: none;
    border: none;
    outline: none;
    font-size: 15px;
  }

  .no-cities {
    text-align: center;
    color: white;
    font-size: 16px;
    margin-top: 20px;
  }

  ul {
    padding: 0;
    list-style: none;
  }

  .weather-title {
    color: white;
  }
}
</style>
